import WXMap from '@/libs/qqmap-wx-jssdk.js';
import { setScancode, setLocationPermissionModal, getLocationPermissionModal } from '@/mixins/info';
import { saveItem, getItem, toast } from './util';
// #ifdef H5
import nativeApi from '@/mixins/nativeApi';
// #endif

// const appType = import.meta.env.VITE_VUE_APP_TYPE;
const mapType = import.meta.env.VITE_VUE_APP_MAP;
// 地图key
const mapKey = import.meta.env.VITE_VUE_APP_KEY;


export interface MarkerLocation {
  lat?: number | undefined; // 纬度 浮点数，范围 -90 ~ 90
  lng?: number | undefined; // 经度 浮点数，范围 -180 ~ 180
  // storageTime?: number; // 存储时间
}

let locationInfo = reactive({
  lat: import.meta.env.VITE_VUE_APP_LOCATION_LAT,// 32.05724,
  lng: import.meta.env.VITE_VUE_APP_LOCATION_LNG,//118.77807,
  cityName: import.meta.env.VITE_VUE_APP_LOCATION_CITY_NAME,//'南京',
  cityCode: import.meta.env.VITE_VUE_APP_LOCATION_CITY_CODE,//'210000',
});

// 获取定位信息
export const getLocationInfo = () => {
  let info = getItem('location');
  if (!info || JSON.stringify(info) === '{}') {
    return locationInfo;
  }
  return info;
};

// 逆向解析
const wxReverseGeocoder = (location: MarkerLocation) => {
  console.log('wxReverseGeocoder--1111-');
  const wechatMapAPI: any = new WXMap({
    key: mapKey,
  });
  return new Promise((resolve, reject) => {
    wechatMapAPI.reverseGeocoder({
      location: {
        latitude: location.lat,
        longitude: location.lng,
      },
      success: (res: any) => {
        console.log('success---', res.result);
        resolve(res.result.ad_info);
      },
      fail: (error: any) => {
        console.log('fail---', error);
        reject(error);
      },
    });
  });
}
const gdReverseGeocoder = (location: MarkerLocation) => {
  return new Promise((resolve, reject) => {
    const url = `https://restapi.amap.com/v3/geocode/regeo?key=${mapKey}&location=${location.lng},${location.lat}`;
    console.log('gd---url---', url);
    uni.request({
      url: url,
      method: 'GET',
      success: (res: any) => {
        console.log('gdres -----success-------', res);

        if (res.data.status === '1') {
          resolve(res.data.regeocode.addressComponent);
        } else {
          reject([]);
        }
      },
      fail: (eror: any) => {
        console.log('gdres -----eror--------', eror);
        reject([]);
      },
    });
  })
}
const reverseGeocoder = async (location: MarkerLocation) => {
  if (mapType === 'wx') {
    return await wxReverseGeocoder(location);
  } else {
    return await gdReverseGeocoder(location);
  }
};

// 获取定位
export const getLocation = () => {
  // 定位
  return new Promise((resolve, reject) => {
    // #ifdef H5
    if (getItem("locationPermisson") === "1" && getLocationPermissionModal() === "0") {
      setLocationPermissionModal("1")
      const hasLocationPermission = nativeApi.hasLocationPermission();
      console.log("hasLocationPermission", hasLocationPermission)
      if (hasLocationPermission === "0") {
        uni.showModal({
          title: '温馨提示',
          content: '为了给您更好的推荐附近电站，请开启定位权限',
          showCancel: true,
          cancelText: '拒绝',
          confirmText: '同意',
          success: (e: any) => {
            if (e.confirm) {
              nativeApi.go2Settings();
              saveItem('location', locationInfo);
              reject(locationInfo);
            } else if (e.cancel) {
              saveItem('location', locationInfo);
              reject(locationInfo);
            }
          },
        })
      } else {
        nativeApi.getLocation().then((res: any) => {
          console.log("getLocation-h5-suc", res)
          saveItem('locationPermisson', "0");
          locationInfo = {
            lat: Number(res.latitude),
            lng: Number(res.longitude),
            cityName: res.city.replace('市', ''),
            cityCode: res.adcode,
          };
          saveItem('location', locationInfo);
          resolve(locationInfo);
        }).catch((err: any) => {
          console.log("getLocation-h5-err", err)
          saveItem('locationPermisson', "1");
          saveItem('location', locationInfo);
          reject(locationInfo);
        })
      }

    } else {
      nativeApi.getLocation().then((res: any) => {
        console.log("getLocation-h5-suc", res)
        saveItem('locationPermisson', "0");
        locationInfo = {
          lat: Number(res.latitude),
          lng: Number(res.longitude),
          cityName: res.city.replace('市', ''),
          cityCode: res.adcode,
        };
        saveItem('location', locationInfo);
        resolve(locationInfo);
      }).catch((err: any) => {
        console.log("getLocation-h5-err", err)
        saveItem('locationPermisson', "1");
        saveItem('location', locationInfo);
        reject(locationInfo);
      })
    }
    // #endif

    // #ifndef H5
    uni.getLocation({
      type: 'gcj02',
      geocode: true,
      highAccuracyExpireTime: 3000,
      success: (res: any) => {
        console.log('success---', res);
        reverseGeocoder({
          lat: res.latitude,
          lng: res.longitude,
        })
          .then((res1: any) => {
            locationInfo = {
              lat: res.latitude,
              lng: res.longitude,
              cityName: res1.city.replace('市', ''),
              cityCode: res1.adcode,
            };
            saveItem('location', locationInfo);
            resolve(locationInfo);
          })
          .catch((error1: any) => {
            locationInfo.lat = res.latitude;
            locationInfo.lng = res.longitude;
            saveItem('location', locationInfo);
            reject(locationInfo);
          });
      },
      fail: (error: any) => {
        console.log('fail---', error);
        saveItem('location', locationInfo);
        reject(locationInfo);
      },
    });
    // #endif
  });
};

export const openLocation = (item: any) => {
  // #ifdef H5
  nativeApi.navigator({
    type: item.type,
    lat: Number(item.stationLat),
    lng: Number(item.stationLng),
  }).catch((err: any) => {
    toast(err.message)
  })
  // #endif
  // #ifdef MP-WEIXIN
  setScancode('2');
  uni.openLocation({
    name: item.stationName,
    address: `${item.areaCodeName}${item.address}`,
    latitude: Number(item.stationLat),
    longitude: Number(item.stationLng),
  });
  // #endif
}

// 搜索相关目的地
const searchKeywordWx = (item: any) => {
  const wechatMapAPI: any = new WXMap({
    key: mapKey,
  });
  // 调用接口
  return new Promise((resolve, reject) => {
    wechatMapAPI.getSuggestion({
      keyword: item.keyword,  //搜索关键词
      location: {
        latitude: item.userLat,
        longitude: item.userLng
      },
      // address_format:'short', // 短地址，缺省时返回长地址，可选值：‘short’
      // location: '39.980014,116.313972',  //设置周边搜索中心点
      // filter:'',
      success: (res: any) => { //搜索成功后的回调
        console.log('searchKeyword', res)
        resolve(res.data || [])
      },
      fail: (res: any) => {
        console.log('searchKeyword2', res);
        reject([])
      }
    });
  })
}
const getDistance = (lat1: number, lng1: number, lat2: number, lng2: number) => {
  var radLat1 = lat1 * Math.PI / 180.0;
  var radLat2 = lat2 * Math.PI / 180.0;
  var a = radLat1 - radLat2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;// EARTH_RADIUS;
  s = Math.round(s * 10000) / 10;
  return s;
}
const searchKeywordGd = (item: any) => {
  console.log('gd------', item);
  return new Promise((resolve, reject) => {
    const url = `https://restapi.amap.com/v5/place/text?key=${mapKey}&keywords=${item.keyword}&location=${item.userLat},${item.userLng}`;
    console.log('gd---url---', url);
    uni.request({
      url: url,
      method: 'GET',
      success: (res: any) => {
        console.log('gdres -----success-------', res);
        if (res.data?.status === '1' && res.data?.pois?.length > 0) {
          const arr: any = [];
          res.data?.pois?.forEach((item1: any) => {
            const loc = item1.location.split(',');
            arr.push({
              title: item1.name,
              address: `${item1.pname}${item1.cityname}${item1.address}`,
              _distance: getDistance(item.userLat, item.userLng, loc[1], loc[0]),
              location: { lng: loc[0], lat: loc[1] }
            });
          });
          console.log('gdres -----success----1---', arr);
          resolve(arr);
        } else {
          reject([]);
        }
      },
      fail: (eror: any) => {
        console.log('gdres -----eror--------', eror);
        reject([]);
      },
    });
  })
}
export const searchKeyword = (item: any) => {
  if (mapType === 'wx') {
    return searchKeywordWx(item);
  } else {
    return searchKeywordGd(item);
  }
}

let searchLocation: any = reactive(null as any);
export const setSearch = (location?: MarkerLocation) => {
  searchLocation = location || null;
}
export const getSearch = () => {
  return searchLocation;
}